package com.cooba.activitys;

import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTabHost;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.TabHost.TabSpec;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.cooba.R;
import com.cooba.application.MyApplication;
import com.cooba.broadCastReceiver.MyReceiver1;
import com.cooba.content_frament.FindFrament;
import com.cooba.content_frament.GameFrament;
import com.cooba.content_frament.HomeFrament;
import com.cooba.content_frament.LivingFrament;
import com.cooba.content_frament.MeFrament;
import com.cooba.content_frament.VideoFrament;
import com.cooba.utils.CarURL;
import com.cooba.utils.CommonUtil;
import com.cooba.utils.HomeWatcher;
import com.cooba.utils.ServerURL;
import com.cooba.utils.SharedPreferencesUtil;
import com.cooba.utils.UpdateManager;
import com.cooba.utils.Utils;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.umeng.analytics.MobclickAgent;
import com.umeng.message.PushAgent;

import org.json.JSONObject;

import java.text.SimpleDateFormat;


/**
 * @author yangyu
 *         功能描述：自定义TabHost
 */
public class MainTabActivity extends FragmentActivity implements HomeWatcher.OnHomePressedListener {

    private MyReceiver1 myReceiver;
    private HomeWatcher mHomeWatcher;
    private boolean flag = true;
    private long lasttime = 0;
    private HttpUtils httpUtils;

    //定义FragmentTabHost对象
    private FragmentTabHost mTabHost;

    //定义一个布局
    private LayoutInflater layoutInflater;

    //定义数组来存放Fragment界面
    private Class fragmentArray[] = {FindFrament.class, LivingFrament.class, HomeFrament.class, VideoFrament.class, MeFrament.class};

    //定义数组来存放按钮图片
    private int mImageViewArray[] = {R.drawable.content_shouye_selector, R.drawable.content_youxi_selector, R.drawable.content_faxian_selector,
            R.drawable.content_yingyin_selector, R.drawable.content_me_selector};

    //Tab选项卡的文字
    private String mTextviewArray[] = {"服务", "直播", "新闻", "影音", "我"};

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_tab_layout);

        PushAgent mPushAgent = PushAgent.getInstance(this);
        String pushSet = SharedPreferencesUtil.getData(this, "push_set", "1");
        if (pushSet.equals("0")) {
            mPushAgent.disable();

        } else {
            mPushAgent.enable();
        }
        PushAgent.getInstance(this).onAppStart();
        IntentFilter intentFilter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
        //intentFilter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
        myReceiver = new MyReceiver1();
        registerReceiver(myReceiver, intentFilter);
        //checkNetState();//检查网络状态
        MyApplication application = MyApplication.getMyApplication();
        if (!application.getIsInCar()) {
            UpdateManager updateManager = new UpdateManager(this);
            //updateManager.checkUpdateInfo();
        }
        initView();
        //initLogin();
        getMac();
    }


    private void getMac() {
        final MyApplication application = MyApplication.getMyApplication();
        if (application.getIsInCar()) {
            HttpUtils httpUtils = new HttpUtils();
            RequestParams params = new RequestParams();
            httpUtils.send(HttpRequest.HttpMethod.POST, CarURL.wifiDog, params, new RequestCallBack<String>() {
                @Override
                public void onSuccess(ResponseInfo<String> responseInfo) {
                    Log.d("wei", "链接服务器成功数据是:" + responseInfo.result);
                    String mac = null;
                    String remainFlow = null;
                    try {
                        mac = JSON.parseObject(responseInfo.result).getString("mac");
                        remainFlow = JSON.parseObject(responseInfo.result).getString("remainFlow");
                        SharedPreferencesUtil.saveData(MainTabActivity.this, "wifimac", mac);
                        SharedPreferencesUtil.saveData(MainTabActivity.this, "remainflow", Utils.FormatSize(Double.valueOf(remainFlow)));

                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                }

                @Override
                public void onFailure(HttpException error, String msg) {
                    Log.d("wei", "链接服务器失败:" + msg);
                }
            });
        }
    }


    /**
     * 初始化组件
     */
    private void initView() {
        //实例化布局对象
        layoutInflater = LayoutInflater.from(this);

        //实例化TabHost对象，得到TabHost
        mTabHost = (FragmentTabHost) findViewById(android.R.id.tabhost);
        mTabHost.setup(this, getSupportFragmentManager(), R.id.realtabcontent);
        mTabHost.getTabWidget().setDividerDrawable(null);
        //得到fragment的个数
        int count = fragmentArray.length;

        for (int i = 0; i < count; i++) {
            //为每一个Tab按钮设置图标、文字和内容
            TabSpec tabSpec = mTabHost.newTabSpec(mTextviewArray[i]).setIndicator(getTabItemView(i));
            //将Tab按钮添加进Tab选项卡中
            mTabHost.addTab(tabSpec, fragmentArray[i], null);
            //设置Tab按钮的背景
            mTabHost.getTabWidget().getChildAt(i).setBackgroundColor(getResources().getColor(R.color.white));
        }
        mTabHost.setCurrentTab(2);
    }

    /**
     * 给Tab按钮设置图标和文字
     */
    private View getTabItemView(int index) {
        View view = layoutInflater.inflate(R.layout.tab_item_view, null);

        ImageView imageView = (ImageView) view.findViewById(R.id.imageview);
        imageView.setImageResource(mImageViewArray[index]);

        TextView textView = (TextView) view.findViewById(R.id.textview);
        textView.setText(mTextviewArray[index]);

        return view;
    }

    /**
     * 检查网络是否连接
     */
    private void checkNetState() {
        if (!CommonUtil.isNetWork(this)) {
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setTitle("网络状态提醒");
            builder.setMessage("当前网络不可用，是否打开网络设置?");
            builder.setNeutralButton("取消", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                }
            });
            builder.setNegativeButton("确定", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    if (android.os.Build.VERSION.SDK_INT > 10) {
                        startActivity(new Intent(android.provider.Settings.ACTION_SETTINGS));
                    } else {
                        startActivity(new Intent(android.provider.Settings.ACTION_WIRELESS_SETTINGS));
                    }
                }
            });
            builder.create().show();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        mHomeWatcher = new HomeWatcher(this);
        mHomeWatcher.setOnHomePressedListener(this);
        mHomeWatcher.startWatch();
        MobclickAgent.onResume(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        mHomeWatcher.setOnHomePressedListener(null);
        mHomeWatcher.stopWatch();
        if (myReceiver != null) {
            unregisterReceiver(myReceiver);
        }
    }

    @Override
    public void onHomePressed() {
        if (System.currentTimeMillis() - lasttime > 2000) {
            lasttime = System.currentTimeMillis();
            String bannerStatistic = CommonUtil.readFileSdcard();
            if (bannerStatistic != null && !bannerStatistic.equals("")) {
                String res = "{" + "\"statisticsList\"" + ":[" + bannerStatistic.substring(0, bannerStatistic.length() - 1) + "]}";
                Log.d("wei", "res:" + res);
                HttpUtils httpUtils = new HttpUtils();
                RequestParams params = new RequestParams();
                params.addBodyParameter("statisticsList", res);
                httpUtils.send(HttpRequest.HttpMethod.POST, ServerURL.httpUrl + ServerURL.bannerStatistic, params, new RequestCallBack<String>() {
                    @Override
                    public void onSuccess(ResponseInfo<String> responseInfo) {
                        Log.d("wei", "链接服务器成功:" + responseInfo.result);
                        String status = null;
                        try {
                            status = JSON.parseObject(responseInfo.result).getString("status");
                            if (status.equals("1")) {
                                CommonUtil.deleteFile();
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                    }

                    @Override
                    public void onFailure(HttpException error, String msg) {
                        Log.d("wei", "链接服务器失败:" + msg);
                    }
                });
            }
        }
    }

    @Override
    public void onHomeLongPressed() {

    }

    //退出程序
    private long timeMillis;

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            if ((System.currentTimeMillis() - timeMillis) > 2000) {
                Toast.makeText(getApplicationContext(), "再按一次退出程序", Toast.LENGTH_SHORT).show();
                timeMillis = System.currentTimeMillis();
            } else {
                finish();
                System.exit(0);
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }


    private void initLogin() {
        String number = SharedPreferencesUtil.getData(this, "login_id", "");
        String password = SharedPreferencesUtil.getData(this, "password", "");
        SimpleDateFormat sDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String create_date = sDateFormat.format(new java.util.Date());
        if (!TextUtils.isEmpty(number) && !TextUtils.isEmpty(password)) {
            HttpUtils http = new HttpUtils();
            RequestParams params = new RequestParams();
            params.addQueryStringParameter("login_id", number);
            params.addQueryStringParameter("password", password);
            params.addQueryStringParameter("login_date", create_date);
            String url = ServerURL.httpUrl + ServerURL.Login;
            http.send(HttpRequest.HttpMethod.POST, url, params, new RequestCallBack<String>() {
                @Override
                public void onSuccess(ResponseInfo<String> responseInfo) {
                    Log.e("wei", "链接服务器成功" + responseInfo.result);
                    String result = null;
                    //JSON的解析过程
                    try {
                        JSONObject jsonObject = new JSONObject(responseInfo.result.toString());
                        result = jsonObject.get("status").toString();
                        if (result.equals("1")) {
                            Toast.makeText(MainTabActivity.this, "登陆成功!", Toast.LENGTH_LONG).show();
                            String allTotalIntegral = jsonObject.get("allTotalIntegral").toString();
                            SharedPreferencesUtil.saveData(MainTabActivity.this, "allTotalIntegral", allTotalIntegral);
                            SharedPreferencesUtil.saveData(MainTabActivity.this, "login_state", "1");//保存登录状态
                        } else {
                            SharedPreferencesUtil.saveData(MainTabActivity.this, "allTotalIntegral", "");
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }

                @Override
                public void onFailure(HttpException error, String msg) {
                    Log.e("ss", "链接服务器失败");
                }
            });
        }
    }

}
